/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.isystem.autpart.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.isystem.autpart.util.HibernateUtil;

/**
 *
 * @author miguel-lap
 */
public class DAO {
    private SessionFactory sessFact;
    private Session session;
    private Transaction tr;

    public DAO() {
        this.sessFact = HibernateUtil.getSessionFactory();
    }
    
    public Session getSession(){
        return sessFact.openSession();
    }

    public void evict(Session s, Object obj) {
        s.evict(obj);
//        sess.flush();
    }

//    public void refresh(Session s) {
////        this.Close();
//        this.Open(s);
//    }

//    public void Open(Session s) {
//
//        this.sessFact = HibernateUtil.getSessionFactory();
//        s = sessFact.openSession();
//        this.tr = sess.beginTransaction();
//    }

//    public void Close() {
//        sess.clear();
//        sess.close();
////        sessFact.close();
//    }

//    public abstract Object load(Object id);
    public Object load(Session s, Class x, Object id) {
        if (s.get(x, (Serializable) id) == null) {
            return null;
        }
        Object p = s.load(x, (Serializable) id);
        return p;
    }

    public void persist(Session s, Object obj) {
//        tr = sess.beginTransaction();
        s.persist(obj);
//        tr.commit();
//        sess.close();
//        sessFact.close();
    }

    public List findAll(Session s, String Hql) {
        Query query = s.createQuery(Hql);
        List result = query.list();
        return result;
    }

    public Object findOne(Session s, String Hql) {
        Query query = s.createQuery(Hql);
        Object result = query.list().get(0);
        return result;
    }

    public void delete(Session s, Object obj) {
//        tr = sess.beginTransaction();
        s.delete(obj);
//        tr.commit();
        //sess.close();
        // sessFact.close();
    }

//    public void update() {
//        tr = sess.beginTransaction();
//        tr.commit();
//    }
    public void update(Session s, Object object) {
//        tr = sess.beginTransaction();
        s.update(object);
//        tr.commit();
    }
    
    public String md5(Session s, String cadena){
        try{
            Query q = s.createSQLQuery("Select md5('" + cadena + "')");
            return (String) q.list().get(0);
        }catch (Exception e){
            System.out.println("error "  + e.getMessage());
            return "";
        }
    }
}